<template>
    <edu-dialog :title="$t('message.prompt')" width="50%" ref="TipDialog" @close="handleClose">
        <div v-if="!checked">您好！您提交的信息已经提交成功!</div>

        <div v-for="(item,outIndex) in viewRows" :key="'viewRow'+outIndex">
            <div v-if="checked">{{item.title}}</div>
            <div v-if="item.desc" class="desc" v-html="item.desc"></div>
            <el-row v-for="(row,index) in item.items" :key="'item'+index" class="diff-list">
                <div
                    class="label"
                    v-if="isMulti"
                >{{label}}{{row.order}}{{row.operType==3?' (已删除)':null}}</div>
                <table cellpadding="8px">
                    <colgroup>
                        <col width="25%" />
                        <col />
                    </colgroup>
                    <tr v-for="(tr,tr_index) in row.stuAttriInfos" :key="'tr'+tr_index">
                        <td style="text-align:right">{{tr.nameZH}}：</td>
                        <td>
                            {{tr.oldColumnValue === null || tr.oldColumnValue === '' ? '无' : tr.oldColumnValue}}
                            <span v-if="row.operType==1">添加</span>
                            <span v-else-if="row.operType==2">改为</span>
                            <span v-else>删除</span>
                            {{ getColumLabel(tr) }}
                        </td>
                    </tr>
                </table>
            </el-row>
        </div>

        <el-row style="margin-top:18px" v-if="checked">
            <el-col :span="4" style="text-align:center;line-height:32px">
                <span class="error-char">*</span>证明材料：
            </el-col>
            <el-col :span="20">
                <el-upload
                    limit="5"
                    ref="fileUpload"
                    class="avatar-uploader"
                    action="/api/commonservice/obsfile/uploadimage"
                    :data="{bucketname: 'face', folderpath: 'file'}"
                    :file-list="fileList"
                    :on-success="handleAvatarSuccess"
                    :on-remove="handleFileRemove"
                    :on-error="handleAvatarError"
                    :before-upload="beforeAvatarUpload"
                >
                    <el-button size="small" type="primary">点击上传</el-button>
                    <div
                        slot="tip"
                        class="el-upload__tip"
                        style="color:red;line-height:18px"
                    >姓名、身份证号、民族等身份信息修改，请上传身份证原件和公安局证明原件的扫描件；火车终点站修改，请上传父母居住地相关证明材料（上传的证明材料，请上传JPG格式）</div>
                    <div slot="tip" class="el-upload__tip">只能上传jpg/jpeg/png/doc/docx文件，且不超过5M</div>
                </el-upload>
            </el-col>
        </el-row>
        <el-row style="margin-top:18px" v-if="checked">
            <el-col :span="4" style="text-align:center;line-height:32px">
                <span class="error-char">*</span>修改说明：
            </el-col>
            <el-col :span="20">
                <el-input
                    type="textarea"
                    rows="4"
                    v-model="modifyDesc"
                    maxlength="255"
                    placeholder="最大长度为255"
                ></el-input>
            </el-col>
        </el-row>
        <span slot="buttons">
            <el-button @click="close">{{$t('label.back')}}</el-button>
            <el-button v-if="checked" @click="save" type="primary">{{$t('message.submit')}}</el-button>
        </span>
    </edu-dialog>
</template>
<script>
import UTILS from "common/src/utils/utils";
import moment from "moment";
import { getCityNameByValue } from "./businessMethods";
export default {
    name: "differenceDialog",
    props: {
        rawData: {
            type: Array,
            default: () => {
                return []
            }
        },
        postData: {
            type: Array,
            default: () => {
                return []
            }
        },
        options: {
            type: Object,
            default: () => {
                return {}
            }
        },
        XJZYOptions: {
            type: Array,
            default: () => {
                return []
            }
        },
        ZYFXMCOptions: {
            type: Array,
            default: () => {
                return []
            }
        },
        checked: {
            type: Boolean, //是否存在审核
            default: false
        },
        citys: {
            type: Array,
            default: () => {
                return []
            }
        },
        endStation: {
            type: Array,
            default: () => {
                return []
            }
        },
        label: {
            type: String,
            default: null
        },
        isMulti: {
            type: Boolean,
            default: false
        }
    },
    data() {
        return {
            userInfo: {},
            viewRows: null,
            checkFieldText: null,
            fileList: [],
            modifyDesc: null
        };
    },
    mounted() {
        // 获取当前用户信息
        if (localStorage.getItem('sessiondata')) {
            if (JSON.parse(localStorage.getItem('sessiondata')).mockUser) {
                this.userInfo = JSON.parse(localStorage.getItem('sessiondata')).mockUser
            } else {
                this.userInfo = JSON.parse(localStorage.getItem('user'))
            }
        }
    },
    methods: {
        // 根据value值获取label值
        getLabelByValue(array, columnValue) {
            if (columnValue === null || columnValue === '') {
                return columnValue
            }
            let option = array.find(
                c => c.value == columnValue
            )
            if (option) {
                return option.label
            } else {
                // 如果没有匹配项取columnValue
                return columnValue
            }
        },
        getColumLabel(tr) {
            // 学籍专业的处理
            if (tr.id === 68 && tr.columnValue && this.XJZYOptions.length > 0) {
                let rightLabel = this.getLabelByValue(this.XJZYOptions, tr.columnValue)
                return rightLabel.split('(')[0] ? rightLabel.split('(')[0] : '无'
            } else if (tr.id === 70 && tr.columnValue && this.ZYFXMCOptions.length > 0) { // 专业方向名称的处理
                let rightLabel = this.getLabelByValue(this.ZYFXMCOptions, tr.columnValue)
                return rightLabel.split('(')[0] ? rightLabel.split('(')[0] : '无'
            } else if (tr.id === 200 && tr.columnValue) { // 处理护照有效日期止的显示
                return moment(tr.columnValue).format("YYYY-MM-DD")
            } else {
                return tr.columnValue ? tr.columnValue : '无'
            }
        },
        open() {
            this.$refs.TipDialog.open();
            this.calculateViewItem();
            if (this.$refs.fileUpload) this.$refs.fileUpload.clearFiles();
            this.fileList = [];
            this.modifyDesc = null;
        },
        close() {
            this.$refs.TipDialog.close();
        },
        handleClose() {
            if (!this.checked) {
                this.$emit("update");
            }
        },
        save() {
            if (this.fileList.length == 0) {
                this.$message({
                    message: "证明材料不能为空",
                    type: "warning"
                });
                return;
            }
            if (!this.modifyDesc) {
                this.$message({
                    message: "修改说明不能为空",
                    type: "warning"
                });
                return;
            }
            let fileNames = this.fileList.map(f => {
                return f.response.data.file.objectkey;
            });
            this.$emit("save-diff", fileNames.join(","), this.modifyDesc);
        },
        setSelectLabel(column, attr) {
            if (
                column &&
                column.hasOwnProperty(attr) &&
                column[attr] != null &&
                column[attr] != ""
            ) {
                let label = "";
                column[attr].split(",").forEach(v => {
                    let oldVal_ = this.options[column.value].find(
                        c => c.value == v
                    );
                    if (oldVal_) {
                        label += oldVal_.label;
                    }
                });
                column[attr] = label;
            }
        },
        convertSelectLabel(columns) {
            columns.forEach(column => {
                if (column.id === 70) {
                    column.oldColumnValue = this.getLabelByValue(this.ZYFXMCOptions, column.oldColumnValue);
                }
                if (
                    column.type != "select" ||
                    !this.options.hasOwnProperty(column.value)
                ) {
                    return;
                }
                if (column.isMulti) {
                    this.setSelectLabel(column, "oldColumnValue");
                    this.setSelectLabel(column, "columnValue");
                } else {
                    if (column.value == "G_XZQY") {
                        column.oldColumnValue = getCityNameByValue(
                            column.oldColumnValue,
                            this.citys
                        );
                        column.columnValue = getCityNameByValue(
                            column.columnValue,
                            this.citys
                        );
                    } else if (column.value == "end_station") {
                        column.oldColumnValue = this.getLabelByValue(this.endStation, column.oldColumnValue);
                        column.columnValue = this.getLabelByValue(this.endStation, column.columnValue);
                    } else if (column.column !== 'MAJOR_CODE_') {
                        let oldVal = this.options[column.value].find(
                            c => c.value == column.oldColumnValue
                        );
                        let newVal = this.options[column.value].find(
                            c => c.value == column.columnValue
                        );
                        if (oldVal) column.oldColumnValue = oldVal.label;
                        if (newVal) column.columnValue = newVal.label;
                    }
                }
            });
        },
        //证明材料上传前验证
        beforeAvatarUpload(file) {
            const isAccept = [
                "image/jpeg",
                "image/jpg",
                "image/png",
                "application/msword",
                "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
            ].includes(file.type);
            const isLt2M = file.size / 1024 / 1024 < 5;
            if (!isAccept) {
                this.$message.error(
                    "证明材料类型错误，只允许上传图片和word文档"
                );
            }
            if (!isLt2M) {
                this.$message.error("上传图片大小不能超过 5MB!");
            }
            return isAccept && isLt2M;
        },
        //证明材料上传失败
        handleAvatarError(res, file) {
            this.$message({
                message: "证明材料上传失败",
                type: "error"
            });
        },
        handleAvatarSuccess(res, file, fileList) {
            this.fileList = fileList;
        },
        handleFileRemove(file, fileList) {
            this.fileList = fileList;
        },
        getDateFormat(val) {
            return val ? moment(val).format("YYYY-MM-DD") : null;
        },
        calculateViewItem() {
            this.viewRows = [];
            if (this.isMulti) {
                this.renderNormalView();
                this.renderSchoolView();
                this.renderCollegeView();
            } else {
                this.renderComplexView();
            }
        },
        renderNormalView() {
            let rows = [];
            let addOrder = this.rawData.filter(raw => raw.id).length + 1;
            this.postData.forEach((row, index) => {
                let cols = row.stuAttriInfos.filter(
                    col => col.isSchoolCheck == 0 && col.isCollegeCheck == 0
                );
                //如果是删除，且包括校审或院审,直接忽略
                if (
                    row.operType == 3 &&
                    row.stuAttriInfos.find(
                        col => col.isSchoolCheck || col.isCollegeCheck
                    )
                ) {
                    return;
                }
                if (cols.length > 0) {
                    this.convertSelectLabel(cols);
                    let order = 0; //修改和删除的排序，一定在新增前
                    this.rawData.forEach((rawRow, rawIndex) => {
                        if (rawRow.id == row.id) {
                            order = rawIndex + 1;
                        }
                    });
                    let newRow = {
                        id: row.id,
                        operType: row.operType,
                        stuAttriInfos: cols,
                        order: order > 0 ? order : addOrder++
                    };
                    this.filterEmptyCol(newRow);
                    rows.push(newRow);
                }
            });
            if (rows.length > 0) {
                this.viewRows.push({
                    title: "修改详情",
                    items: _.sortBy(rows, [o => o.order])
                });
            }
        },
        filterEmptyCol(newRow) {
            //若为删除行，过滤空字段
            if (newRow.operType == 3 && newRow.stuAttriInfos.length > 0) {
                newRow.stuAttriInfos = newRow.stuAttriInfos.filter(col => {
                    if (col.oldColumnValue == "") col.oldColumnValue = null;
                    if (col.columnValue == "") col.columnValue = null;
                    return col.oldColumnValue == null && col.columnValue == null
                        ? false
                        : true;
                });
            }
        },
        renderSchoolView() {
            let rows = [];
            let columnNames = [];
            let addOrder = this.rawData.filter(raw => raw.id).length + 1;
            this.postData.forEach((row, index) => {
                let cols = row.stuAttriInfos.filter(col => col.isSchoolCheck);
                if (cols.length > 0) {
                    this.convertSelectLabel(cols);
                    let order = 0; //修改和删除的排序，一定在新增前
                    this.rawData.forEach((rawRow, rawIndex) => {
                        if (rawRow.id == row.id) {
                            order = rawIndex + 1;
                        }
                    });
                    cols.forEach(col => {
                        if (!columnNames.includes(col.nameZH)) {
                            columnNames.push(col.nameZH);
                        }
                    });
                    rows.push({
                        id: row.id,
                        operType: row.operType,
                        stuAttriInfos: cols,
                        order: order > 0 ? order : addOrder++
                    });
                }
            });
            if (rows.length > 0) {
                this.viewRows.push({
                    title: "校审详情",
                    desc: `您提交的信息中，<span style='color:red'>${columnNames.join(
                        ","
                    )}</span>需要校审审核，请提交相关证明材料并填写修改说明!`,
                    items: _.sortBy(rows, [o => o.order])
                });
            }
        },
        renderCollegeView() {
            let rows = [];
            let columnNames = [];
            let addOrder = this.rawData.filter(raw => raw.id).length + 1;
            this.postData.forEach((row, index) => {
                let cols = row.stuAttriInfos.filter(col => col.isCollegeCheck);
                if (cols.length > 0) {
                    this.convertSelectLabel(cols);
                    let order = 0; //修改和删除的排序，一定在新增前
                    this.rawData.forEach((rawRow, rawIndex) => {
                        if (rawRow.id == row.id) {
                            order = rawIndex + 1;
                        }
                    });
                    cols.forEach(col => {
                        if (!columnNames.includes(col.nameZH)) {
                            columnNames.push(col.nameZH);
                        }
                    });
                    rows.push({
                        id: row.id,
                        operType: row.operType,
                        stuAttriInfos: cols,
                        order: order > 0 ? order : addOrder++
                    });
                }
            });
            if (rows.length > 0) {
                this.viewRows.push({
                    title: "院审详情",
                    desc: `您提交的信息中，<span style='color:red'>${columnNames.join(
                        ","
                    )}</span>需要院审审核，请提交相关证明材料并填写修改说明!`,
                    items: _.sortBy(rows, [o => o.order])
                });
            }
        },
        renderComplexView() {
            let fn = (expression, title, showNames = true) => {
                let cols_ = [];
                this.postData.forEach((row, index) => {
                    let cols = row.stuAttriInfos.filter(expression);
                    if (cols.length > 0) {
                        cols_ = cols_.concat(cols);
                    }
                });
                if (cols_.length > 0) {
                    cols_ = cols_.map(col => {
                        return {
                            id: col.fieldId,
                            oldColumnValue: col.oldColumnValue,
                            columnValue: col.columnValue,
                            isMulti: col.isMulti,
                            type: col.type,
                            value: col.value,
                            nameZH: col.nameZH
                        };
                    });
                    this.convertSelectLabel(cols_);
                    let desc = null;
                    if (showNames) {
                        let dept = title.substring(0, 2);
                        let fieldNames = cols_.map(col => col.nameZH).join(",");
                        desc = `您提交的信息中，<span style='color:red'>${fieldNames}</span>需要${dept}审核，请提交相关证明材料并填写修改说明!`;
                    }
                    this.viewRows.push({
                        title: title,
                        items: [
                            {
                                operType: 2, //修改
                                stuAttriInfos: cols_
                            }
                        ],
                        desc: desc
                    });
                }
            };
            fn(
                col => col.isSchoolCheck == 0 && col.isCollegeCheck == 0,
                "修改详情",
                false
            );
            fn(col => col.isSchoolCheck, "校审详情");
            fn(col => col.isCollegeCheck, "院审详情");
        }
    }
};
</script>
<style lang="scss" scope>
.edu-page-title {
    & > span {
        cursor: pointer;
        display: inline-block;
        padding: 0 10px;
        color: #4c5c70;
        font-size: 16px;
    }
    & > span.active {
        color: #409eff;
    }
}
.error-char {
    color: red;
    margin-right: 3px;
}
.desc {
    margin: 10px 30px;
}
.diff-list {
    margin: 10px 0;
    div {
        margin-bottom: 5px;
    }
    table {
        width: 100%;
        border-collapse: collapse;
        border: 2px solid #999999;
    }
    td {
        border-collapse: collapse;
        border: 1px solid #999999;
    }
    tr td:first-child {
        background: #f5f7f9;
    }
    .label {
        color: #858e9b;
        font-weight: bold;
    }
}
</style>
